package juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProdCustomer_TraditionDemo {
	public static void main(String args[]) {
		ShareData shareData = new ShareData();
		new Thread(() -> {
			for (int i = 0; i < 5; i++) {
				shareData.increment();
			}
		}).start();
		new Thread(() -> {
			for (int i = 0; i < 5; i++) {
				shareData.decrement();
			}
		}).start();
		new Thread(() -> {
			for (int i = 0; i < 5; i++) {
				shareData.increment();
			}
		}).start();
		new Thread(() -> {
			for (int i = 0; i < 5; i++) {
				shareData.increment();
			}
		}).start();
	}
}

class ShareData {
	private int num = 0;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	public void increment() {
		lock.lock();
		try {
			while (num != 0) {
				condition.await();
			}
			num++;
			System.out.println(Thread.currentThread().getName() + " 生产: " + num);
			condition.signalAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void decrement() {
		lock.lock();
		try {
			while (num == 0) {
				condition.await();
			}
			num--;
			System.out.println(Thread.currentThread().getName() + " 消费: " + num);
			condition.signalAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}